package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.user.app.AppUserBatchSendMsgDto;
import com.uzai.console.dto.user.app.AppUserGroupSendMsgDto;
import com.uzai.console.dto.user.app.AppUserQuery;
import com.uzai.console.dto.user.app.AppUserSendMsgBatchDto;
import com.uzai.console.entity.AppUser;
import com.uzai.console.entity.GroupSendJob;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.AppUserMapper;
import com.uzai.console.mapper.GroupSendJobMapper;
import com.uzai.console.service.user.AppUserGroupSendMsgService;
import com.uzai.console.service.user.AppUserSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class AppUserGroupSendMsgServiceImpl implements AppUserGroupSendMsgService {

    private Logger logger = LoggerFactory.getLogger(AppUserGroupSendMsgServiceImpl.class);

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private AppUserSyncService appUserSyncService;

    /**
     * 查询结果添加群发任务
     *
     * @param wechatUserBatchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void groupSendMsg(AppUserBatchSendMsgDto wechatUserBatchSendMsgDto) {
//
//        if(true){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "活动期间，禁止群发功能");
//        }

        if (wechatUserBatchSendMsgDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //获取群发消息任务内容
        AppUserGroupSendMsgDto wechatUserGroupSendMsgDto = wechatUserBatchSendMsgDto.getWechatUserGroupSendMsgDto();
        wechatUserGroupSendMsgDto.setMerId(wechatUserBatchSendMsgDto.getMerId());

        if (wechatUserGroupSendMsgDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if (StringUtils.isBlank(wechatUserGroupSendMsgDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入任务名称");
        }

        if (wechatUserGroupSendMsgDto.getTimeInterval() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入发送时间间隔");
        }

        if (StringUtils.isBlank(wechatUserGroupSendMsgDto.getContent())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        if (wechatUserGroupSendMsgDto.getBeginTime() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入开始时间");
        }

        AppUserQuery wechatUserQuery = wechatUserBatchSendMsgDto.getWechatUserQuery();
        wechatUserQuery.setCurrent(1);//从第一页开始
        wechatUserQuery.setSize(10);
        wechatUserQuery.setMerId(wechatUserBatchSendMsgDto.getMerId());
        //免打扰时间
        Integer busyTimeInterval = wechatUserGroupSendMsgDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if (busyTimeInterval != null) {
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = wechatUserGroupSendMsgDto.getBeginTime() - busyTimeInterval * 3600;
            wechatUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总用户数
        //查询总数
        Integer count = appUserMapper.findCount(wechatUserQuery);

        if (Tools.getInteger(count).intValue() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果为空");
        }

        Integer now = DateUtil.getNowTime();
        //添加群发消息主任务
        GroupSendJob groupSendJobParent = new GroupSendJob();
        groupSendJobParent.setId(IdWorker.getId());
        groupSendJobParent.setParentId(0L); //主任务
        groupSendJobParent.setMerId(wechatUserBatchSendMsgDto.getMerId());
        groupSendJobParent.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
        groupSendJobParent.setName(wechatUserGroupSendMsgDto.getName());
        groupSendJobParent.setSource(GroupSendJobSourceEnum.PRIVATE_USER.getId());
        groupSendJobParent.setContent(wechatUserGroupSendMsgDto.getContent());
        groupSendJobParent.setStatus(GroupSendStatusEnum.INIT.getValue());
        //groupSendJobParent.setTotalCount(count);
        groupSendJobParent.setTotalCount(0); //默认为0
        groupSendJobParent.setFinishCount(0);
        groupSendJobParent.setTimeInterval(wechatUserGroupSendMsgDto.getTimeInterval());
        groupSendJobParent.setBeginTime(wechatUserGroupSendMsgDto.getBeginTime());
        groupSendJobParent.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
        groupSendJobParent.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserGroupSendMsgDto.getUserLabList())));
        groupSendJobParent.setCleanLab(wechatUserGroupSendMsgDto.getCleanLab());
        groupSendJobParent.setUserRemark(Tools.getStr(wechatUserGroupSendMsgDto.getUserRemark()));
        groupSendJobParent.setNightTime(wechatUserGroupSendMsgDto.getNightTime());
        groupSendJobParent.setBusyTimeInterval(wechatUserGroupSendMsgDto.getBusyTimeInterval());
        groupSendJobParent.setSendStartTime(wechatUserGroupSendMsgDto.getBeginTime());
        groupSendJobParent.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserQuery.getNameExcludeList())));
        groupSendJobParent.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserQuery.getRemarkExcludeList())));
        groupSendJobParent.setCreateTime(now);
        groupSendJobParent.setUpdateTime(now);
        groupSendJobMapper.insertSelective(groupSendJobParent);

        try {
            //设置群发消息主任务id
            wechatUserBatchSendMsgDto.setGroupSendJobParentId(groupSendJobParent.getId());
            //后台线程创建子任务和发送消息
            appUserSyncService.sendMessageToUserSelectedSync(wechatUserBatchSendMsgDto);

        } catch (Exception e) {

        }
    }

    /**
     * 查询结果添加群发任务
     *
     * @param wechatUserSendMsgBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void groupSendMsgBatch(AppUserSendMsgBatchDto wechatUserSendMsgBatchDto) {

//        if(true){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "活动期间，禁止群发功能");
//        }

        List<Long> idList = wechatUserSendMsgBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //获取群发消息任务内容
        AppUserGroupSendMsgDto wechatUserGroupSendMsgDto = wechatUserSendMsgBatchDto.getWechatUserGroupSendMsgDto();
        wechatUserGroupSendMsgDto.setMerId(wechatUserSendMsgBatchDto.getMerId());
        if (wechatUserGroupSendMsgDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if (StringUtils.isBlank(wechatUserGroupSendMsgDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入任务名称");
        }

        if (wechatUserGroupSendMsgDto.getTimeInterval() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入发送时间间隔");
        }

        if (StringUtils.isBlank(wechatUserGroupSendMsgDto.getContent())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        if (wechatUserGroupSendMsgDto.getBeginTime() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入开始时间");
        }

        //能发送的用户总数，页面选择的用户由于需要验证免打扰时间，也许不会发送
        List<Long> sendIdList = new ArrayList<>();
        if (idList != null && idList.size() > 0) {
            //免打扰时间
            Integer busyTimeInterval = wechatUserGroupSendMsgDto.getBusyTimeInterval();
            //页面设置了免打扰时间(页面填写的是天数)
            if (busyTimeInterval != null) {
                //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
                int busyGroupSendMsgTime = wechatUserGroupSendMsgDto.getBeginTime() - busyTimeInterval * 3600;
                for (Long id : idList) {
                    AppUser wechatUser = appUserMapper.selectById(id, wechatUserSendMsgBatchDto.getMerId());
                    if (wechatUser != null) {
                        if (Tools.getInteger(wechatUser.getLastGroupSendTime()).intValue() < busyGroupSendMsgTime) {
                            sendIdList.add(wechatUser.getId());
                        }
                    }
                }
            } else {
                for (Long id : idList) {
                    sendIdList.add(id);
                }
            }

            if (sendIdList == null || sendIdList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有符合条件的用户");
            } else {
                wechatUserSendMsgBatchDto.setIdList(sendIdList);
            }

            Integer now = DateUtil.getNowTime();
            //添加群发消息主任务
            GroupSendJob groupSendJobParent = new GroupSendJob();
            groupSendJobParent.setId(IdWorker.getId());
            groupSendJobParent.setParentId(0L); //主任务
            groupSendJobParent.setMerId(wechatUserSendMsgBatchDto.getMerId());
            groupSendJobParent.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            groupSendJobParent.setName(wechatUserGroupSendMsgDto.getName());
            groupSendJobParent.setSource(GroupSendJobSourceEnum.PRIVATE_USER.getId());
            groupSendJobParent.setContent(wechatUserGroupSendMsgDto.getContent());
            groupSendJobParent.setStatus(GroupSendStatusEnum.INIT.getValue());
            //groupSendJobParent.setTotalCount(sendIdList.size());
            groupSendJobParent.setTotalCount(0); //默认发送总数为0
            groupSendJobParent.setFinishCount(0);
            groupSendJobParent.setTimeInterval(wechatUserGroupSendMsgDto.getTimeInterval());
            groupSendJobParent.setBeginTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJobParent.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
            groupSendJobParent.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserGroupSendMsgDto.getUserLabList())));
            groupSendJobParent.setCleanLab(wechatUserGroupSendMsgDto.getCleanLab());
            groupSendJobParent.setUserRemark(wechatUserGroupSendMsgDto.getUserRemark());
            groupSendJobParent.setNightTime(wechatUserGroupSendMsgDto.getNightTime());
            groupSendJobParent.setBusyTimeInterval(wechatUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJobParent.setSendStartTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJobParent.setCreateTime(now);
            groupSendJobParent.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJobParent);

            try {
                //设置群发消息主任务id
                wechatUserSendMsgBatchDto.setGroupSendJobParentId(groupSendJobParent.getId());
                //后台线程创建子任务和发送消息
                appUserSyncService.sendMessageToUserBatchSync(wechatUserSendMsgBatchDto);
            } catch (Exception e) {

            }
        }
    }
}
